package com.api.syh56.shengyunhui.controller;


import com.alibaba.fastjson.JSONObject;
import com.api.syh56.shengyunhui.common.CommonResult;
import com.api.syh56.shengyunhui.common.ResultCode;
import com.api.syh56.shengyunhui.entity.common.ApiAreaDb;
import com.api.syh56.shengyunhui.mapper.ApiAreaDbMapper;
import com.api.syh56.shengyunhui.service.ApiAreaDbService;
import com.api.syh56.shengyunhui.util.AliOssUtil;
import com.api.syh56.shengyunhui.util.AnalysAddressUtil;
import com.api.syh56.shengyunhui.util.HttpUtil;
import com.api.syh56.shengyunhui.util.JWTUtils;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 常用接口
 */
@RestController
@RequestMapping("common")
@Slf4j
public class CommonController {


    @Autowired
    private AliOssUtil aliOssUtil;

    @Autowired
    private ApiAreaDbMapper apiAreaDbMapper;

    @Autowired
    private ApiAreaDbService apiAreaDbService;



    /**
     * OSS图片上传
     * @param file
     * @return
     */
    @PostMapping("/upload_pic")
    public CommonResult<String> upload(MultipartFile file){
        log.info("文件上传：{}",file);

        String OSSfilePath = aliOssUtil.upload(file);
        if(OSSfilePath != null){
            return CommonResult.success(OSSfilePath);
        }
        else{
            return CommonResult.failed(ResultCode.FAILED);
        }
    }

    /**
     * token测试
     * @param token
     * @return
     */
    @PostMapping("/tokentest")
    public Map<String,Object> test(@RequestHeader(name = "token") String token){
        System.out.println(token);
        Map<String,Object> map = new HashMap<>();
        try {
            // 验证令牌
            DecodedJWT verify = JWTUtils.verify(token);
            map.put("state",true);
            map.put("msg","请求成功");
            return map;
        } catch (SignatureVerificationException e) {
            e.printStackTrace();
            map.put("msg","无效签名！");
        }catch (TokenExpiredException e){
            e.printStackTrace();
            map.put("msg","token过期");
        }catch (AlgorithmMismatchException e){
            e.printStackTrace();
            map.put("msg","算法不一致");
        }catch (Exception e){
            e.printStackTrace();
            map.put("msg","token无效！");
        }
        map.put("state",false);
        return map;
    }


    /**
     * 获取 省、市、区 名称
     * @return
     */
    @PostMapping("getCity")
    public CommonResult<List<ApiAreaDb> > getCity(){
        QueryWrapper<ApiAreaDb> apiAreaDbQueryWrapper = new QueryWrapper<>();
//        apiAreaDbQueryWrapper.lambda().like(ApiAreaDb::getAdCode,"___100");
        apiAreaDbQueryWrapper.lambda().orderByAsc(ApiAreaDb::getAdCode);
        List<ApiAreaDb> apiAreaDbs = apiAreaDbMapper.selectList(apiAreaDbQueryWrapper);
        return CommonResult.success(apiAreaDbs);
    }


    /**
     *请求
     */
    @GetMapping("getBankName")
    public CommonResult<Object> getBankName(String cardNo) throws Exception {
        String url = "https://ccdcapi.alipay.com/validateAndCacheCardInfo.json";
        Map<String, String> map = new HashMap<String, String>();
        map.put("cardNo", cardNo);
        map.put("cardBinCheck", "true");
        String json_Str = HttpUtil.send(url, map, "utf-8");
        JSONObject json_obj= JSONObject.parseObject(json_Str);
        System.out.println(json_obj.get("bank")+"");
        return CommonResult.success(json_obj);
    }

    /**
     * 解析详细地区 和址获取 省市  City的adcode
     */
    @GetMapping("analysAddress")
    public CommonResult<Object> analysAddress(String detailedAddress) {

        System.out.println(detailedAddress);

//        addressMap.put("province", province);
//        addressMap.put("city", city);
//        addressMap.put("district", county);
//        addressMap.put("address", street);
        Map<String, String> addressMap = AnalysAddressUtil.spliceDetailedAddress(detailedAddress);

        for (Map.Entry<String, String> entry : addressMap.entrySet()) {
            System.out.println(entry.getKey() + " = " + entry.getValue());
        }


//        QueryWrapper<ApiAreaDb> apiAreaDbQueryWrapper = new QueryWrapper<>();
        String cityN = addressMap.get("city");
        String provinceN = addressMap.get("province");
        if (cityN.equals("中山市") || cityN.equals("东莞市") || cityN.equals("儋州市") || cityN.equals("嘉峪关") ) {
            ApiAreaDb cityArea = apiAreaDbService.selectByCity(cityN);
            String provinceCode = cityArea.getParentCode();
            ApiAreaDb provinceArea = apiAreaDbService.selectByAdCode(provinceCode);

            addressMap.put("province", provinceArea.getName());

            addressMap.put("city", cityArea.getName());
            addressMap.put("adCode", cityArea.getAdCode());
            addressMap.put("addressLocation", cityArea.getCenter());
            addressMap.put("district", "   ");
            return CommonResult.success(addressMap);
        }

        if (provinceN.equals("澳门特别行政区") || provinceN.equals("香港特别行政区")){
            ApiAreaDb apiAreaDb = apiAreaDbService.selectByDistrict(cityN);
            String parentCode = apiAreaDb.getParentCode();
            ApiAreaDb proArea = apiAreaDbService.selectByAdCode(parentCode);
            addressMap.put("province",proArea.getName());
            addressMap.put("city", apiAreaDb.getName());
            addressMap.put("adCode",apiAreaDb.getAdCode());
            addressMap.put("addressLocation",apiAreaDb.getCenter());
            addressMap.put("district",apiAreaDb.getName());
            return CommonResult.success(addressMap);
        }


        //判断省份名称是否是直辖市
//        String province = addressMap.get("province");
//        if (province.equals("北京市") || province.equals("上海市") ||
//                province.equals("天津市") || province.equals("重庆市")) {
//            addressMap = getCorrectName(addressMap);
//        }//如果不是直辖市，
//        else {
//            String city = addressMap.get("city");
//            ApiAreaDb cityArea = apiAreaDbService.selectByCity(city);
//            addressMap.put("adCode", cityArea.getAdCode());
//            addressMap.put("addressLocation",cityArea.getCenter());
//        }

        //判断district是否为null，如果是null则使用city作为district
        String district = addressMap.get("district");
        if (district == null) {
            String city = addressMap.get("city");
            addressMap.put("district", city);
        }
        //根据district查找adCode
        district = addressMap.get("district");
        QueryWrapper<ApiAreaDb> apiAreaDbQueryWrapper = new QueryWrapper<>();
        apiAreaDbQueryWrapper.lambda().eq(ApiAreaDb::getName, district).eq(ApiAreaDb::getLevel, "district");
        List<ApiAreaDb> list = apiAreaDbService.list(apiAreaDbQueryWrapper);
//        System.out.println(list);
        if (list.size() == 0) {
            return CommonResult.failed(ResultCode.FAILED);
        }else if (list.size() == 1){
            ApiAreaDb districtArea = apiAreaDbService.selectByDistrict(district);
            String cityCode = districtArea.getParentCode();
            ApiAreaDb cityArea = apiAreaDbService.selectByAdCode(cityCode);
            String provinceCode = cityArea.getParentCode();
            ApiAreaDb provinceArea = apiAreaDbService.selectByAdCode(provinceCode);

            addressMap.put("province", provinceArea.getName());

            addressMap.put("city", cityArea.getName());
            addressMap.put("adCode", cityArea.getAdCode());
            addressMap.put("addressLocation", cityArea.getCenter());

            addressMap.put("district", districtArea.getName());
        }else {
            String province = addressMap.get("province");
            if (province.equals("北京市") || province.equals("上海市") ||
                    province.equals("天津市") || province.equals("重庆市")) {
//                addressMap = getCorrectName(addressMap);
                addressMap.put("city", province.substring(0,province.length()-1)+"城区");
                ApiAreaDb zhixiashi = apiAreaDbService.selectByCity(addressMap.get("city"));
                addressMap.put("adCode", zhixiashi.getAdCode());
                addressMap.put("addressLocation",zhixiashi.getCenter());
            }//如果不是直辖市，
            else {
                String city = addressMap.get("city");
                ApiAreaDb cityArea = apiAreaDbService.selectByCity(city);
                addressMap.put("adCode", cityArea.getAdCode());
                addressMap.put("addressLocation",cityArea.getCenter());
            }
        }




        return CommonResult.success(addressMap);
    }

    Map<String,String> getCorrectName(Map<String,String> map) {
        String province = map.get("province");
        String city = map.get("city");

        String district = city;
        map.put("district",city);
        //根据真实district查找直辖市的city
        ApiAreaDb child = apiAreaDbService.selectByDistrict(district);

        String parentCode = child.getParentCode();
        ApiAreaDb parent = apiAreaDbService.selectByAdCode(parentCode);

        city = parent.getName();
        String adCode = parent.getAdCode();
        map.put("city", city);
        map.put("adCode",adCode);
        map.put("addressLocation",parent.getCenter());

        return map;
    }







}
